package com.sunday.aomicaichang.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sunday.common.alipay.PayResult;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.constValues.ConstValue;
import com.sunday.aomicaichang.ui.recharge.RechargeSuccessActivity;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.entity.order.PrePayResult;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by yun_sheng on 2017/6/5.
 */

public class PayConfirmActivity extends BaseActivity {


    @Bind(R.id.pay_money)
    TextView payMoney;
    @Bind(R.id.img_alipay)
    ImageView imgAlipay;
    @Bind(R.id.img_wechat)
    ImageView imgWechat;
    @Bind(R.id.btn_next)
    TextView btnNext;
    @Bind(R.id.back)
    ImageView back;

    private OrderItem order;
    private int payType;//1:支付宝 2://微信支付
    private int orderType = 1;//订单支付
    private String money, orderId;
    private IWXAPI api;
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_pay);
        ButterKnife.bind(this);
        order = (OrderItem) getIntent().getSerializableExtra("order");
        type = getIntent().getIntExtra("type", -1);
        initView();
        api = WXAPIFactory.createWXAPI(this, ConstValue.APP_ID);
        api.registerApp(ConstValue.APP_ID);
        if (!api.isWXAppInstalled()) {
            ToastUtils.showToast(mContext, "没有安装微信");
        }
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final UIAlertView dialog = new UIAlertView(mContext, null, "您还未支付，是否返回？", "返回", "去支付");
                dialog.show();
                dialog.setClicklistener(new UIAlertView.ClickListenerInterface() {
                    @Override
                    public void doRight() {
                        dialog.dismiss();
                    }

                    @Override
                    public void  doLeft() {
                        //取消订单
                       Intent intent=new Intent(mContext,BuyOrderListActivity.class);
                        intent.putExtra("page", 1);
                        startActivity(intent);
                        finish();
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    private void initView() {
        if (order == null) {
            return;
        }
        money = String.format("%s", order.getPayAmount().setScale(2, RoundingMode.HALF_UP));
        if (type == 1) {
            orderId = String.valueOf(order.getId());
        } else if (type == 0) {
            orderId = order.getOrderIds();
        } else {
            orderId = order.getOrderIds();
        }
        payMoney.setText(money);
        imgAlipay.setSelected(true);
        payType = 1;
        orderType = order.getType();
    }

    @OnClick({R.id.img_alipay, R.id.img_wechat, R.id.btn_next})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_alipay:
                imgAlipay.setSelected(true);
                imgWechat.setSelected(false);
                payType = 1;
                break;
            case R.id.img_wechat:
                imgAlipay.setSelected(false);
                imgWechat.setSelected(true);
                payType = 2;
                break;
            case R.id.btn_next:
                if (order == null) {
                    return;
                }
                prePayOrder();
                break;
        }
    }


    private PrePayResult prePayResult;

    private void prePayOrder() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"payType", "orderIds", "type", "nonce"};
        String[] str2 = new String[]{String.valueOf(payType), orderId, String.valueOf(orderType), nonce};
        Call<ResultDO<PrePayResult>> call = MemberClient.getApiAdapter().preparePay(payType, orderId, orderType, nonce,
                SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<PrePayResult>>() {
            @Override
            public void onResponse(Call<ResultDO<PrePayResult>> call, Response<ResultDO<PrePayResult>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() != null) {
                        prePayResult = response.body().getResult();
                        BaseApp.getInstance().setOrder(order);
                        if (payType == 1) {
                            aliPay();
                        } else {
                            weChatPay();
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ResultDO<PrePayResult>> call, Throwable t) {

            }
        });
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    private void aliPay() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PayConfirmActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(prePayResult.getAlipayResult(), true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    //Log.e("支付宝信息",payResult.toString());
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(mContext, "支付成功",
                                Toast.LENGTH_SHORT).show();
                        Intent intent = null;
                        if (orderType == 1) {
                            intent = new Intent(mContext, PaySuccessActivity.class);//支付成功界面
                            BigDecimal bigDecimal;
                            if (order.getSendAmount() != null)
                                bigDecimal = order.getPayAmount().subtract(order.getSendAmount());
                            else
                                bigDecimal = order.getPayAmount();
                            intent.putExtra("totalMoney", String.format("￥%s", bigDecimal.setScale(2, RoundingMode.HALF_UP)));
                            intent.putExtra("address", order.getReceiveAddress());
                            intent.putExtra("name", order.getReceiveName());
                            intent.putExtra("mobile", order.getReceiveMobile());
                        } else {
                            intent = new Intent(mContext, RechargeSuccessActivity.class);//支付成功界面
                            intent.putExtra("totalMoney", String.format("￥%s", order.getPayAmount().setScale(2, RoundingMode.HALF_UP)));
                        }
                        startActivity(intent);
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(mContext, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

    };


    private void weChatPay() {
        PayReq req = new PayReq();
        req.appId = prePayResult.getAppId();
        req.partnerId = prePayResult.getParterId();
        req.prepayId = prePayResult.getPrepayId();
        req.nonceStr = prePayResult.getNonceStr();
        req.timeStamp = prePayResult.getTimeStamp();
        req.packageValue = "Sign=WXPay";
        req.sign = prePayResult.getPaySign();
        req.extData = "app data";
        api.sendReq(req);
    }


}
